/*
 * 省级列表js
 * 依赖组件['jquery', 'bootstrapTable', 'bootstrapTableZh']
 */
(function() {
	
	require(['jquery', 'box', 'dynamicTable', 'bootstrapTable', 'bootstrapTableZh', 'select2', 'datetimepickerZh', 'form'], 
			function(jquery, dynamicTable) {
		
		if(typeof jQuery === 'undefined') {	//检测jquery依赖项
			throw new Error('jquery依赖项未能加载');
		}
		
		if(typeof $.fn.bootstrapTable === 'undefined') {	//检测bootstrapTable依赖项
			throw new Error('bootstrapTable依赖项未能加载');
		}
		
		var $table = $('#provincial_list'),	//jquery包装table对象，使其能够调用扩展后jquery的方法
	    	selections = [];
		
		function initTable() {	//加载内容
	        $table.bootstrapTable({
				width: '90%',
				columns: [
 	      			{width: '12%', field: 'year', title: '年度', align: 'center'},
	      			{width: '20%', field: 'commitTime', title: '申报时间', align: 'center'},
	      			{width: '15%', field: 'timesOfReport', title: '第几次申报', align: 'center'},
	      			{width: '20%', field: 'projectStatus', title: '申报状态', align: 'center'},
	      			{width: '15%', field: 'auditResult', title: '评定等级', align: 'center'},
	      			{width: '15%', field: 'crud', title: '操作', align: 'center', events:reportListEvent, formatter: operateFormatter}]
	        });
	        
	        setTimeout(function () {
	            $table.bootstrapTable('resetView');
	        }, 200);
	        
	        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
	        	/*$detail.html('Loading from ajax request...');
	        	var detail = dynamicTable.getCheckStateReport();
	        	$detail.html(detail);*/
	        });
	        
	        $table.on('all.bs.table', function (e, name, args) {
	            console.log(name, args);
	        });
	    }
		
	    function getIdSelections() {
	        return $.map($table.bootstrapTable('getSelections'), function (row) {
	            return row.id;
	        });
	    }
	    
	    function responseHandler(res) {
	        $.each(res.rows, function (i, row) {
	            row.state = $.inArray(row.id, selections) !== -1;
	        });
	        return res;
	    }
	    
	    function detailFormatter(index, row) {
	    	var tableContent = dynamicTable.getCheckStateReport();
	    }
	    
	    function operateFormatter(value, row, index) {
	    	if(row.projectStatus == "保存"){
	    		return ['<a class="edit" href="javascript:void(0)" title="修改申报表">',
			            '<i class="glyphicon glyphicon-edit"></i>',
			            '</a>',
			            '<a title="没有审核表">',
			            '<i class="glyphicon glyphicon-minus"></i>',,
			            '</a>'].join('');
	    	} else {
	    		if(row.auditResult == '未评定') {
	    			return ['<a class="check" href="javascript:void(0)" title="查看申报表">',
				            '<i class="glyphicon glyphicon-eye-open"></i>',
				            '</a>',
				            '<a title="没有审核表">',
				            '<i class="glyphicon glyphicon-minus"></i>',
				            '</a>'].join('');
	    		} else if(row.projectStatus == "建议修改") {
	    			return ['<a class="reCreate" href="javascript:void(0)" title="重新填报申报表">',
				            '<i class="glyphicon glyphicon-refresh"></i>',
				            '</a>',
				            '<a class="checkAudit" href="javascript:void(0)" title="查看审核表">',
				            '<i class="glyphicon glyphicon-thumbs-up"></i>',
				            '</a>'].join('');
	    		} else {
	    			return ['<a class="check" href="javascript:void(0)" title="查看申报表">',
				            '<i class="glyphicon glyphicon-eye-open"></i>',
				            '</a>',
				            '<a class="checkAudit" href="javascript:void(0)" title="查看审核表">',
				            '<i class="glyphicon glyphicon-thumbs-up"></i>',
				            '</a>'].join('');
	    		}
	    	}
	    }
	    
	    window.reportListEvent = {
		        'click .edit': function (e, value, row, index) {
		        	$('#contentNav').data('provinceState', {'reportId': row.id, type: "edit", rowdata: row});
		        	$('#contentNav').data("regionTarget").selectItem(0);
		        },
		        'click .check': function (e, value, row, index) {
		        	var targetPhaseList = row.targetPhaseList, //实施期目标名称
		        		auditData = row.auditData,
		        		targetAttribute = {},		//目标属性
						annualTargetDatalist = {},	//年度目标数组
						indexdata = {};	//指标，包括：实施期、年度 
		        	
		        	orange.loadPage(
	        			{url: "system/getPage.service?path=manage/common/staticReport",
						 target: "checkReport_modal_body", 
						 selector: "#staticReportTable", 
						 success: function(response){
					        var modal = $('#checkReport'), i=0, len=targetPhaseList? targetPhaseList.length: 0, targetPhaseOne ={};
					        //给form表单回显数据
					        $('#staticTable').form('load',row);
					        //弹出模态框
					        modal.modal({backdrop: "static"});
					        //给table赋值
					        for(i=0; i<len; i++) {
					        	targetPhaseOne = targetPhaseList[i];
								var targetNameOfImplphase = targetPhaseOne.targetNameOfImplphase; //实施期目标名称
								var targetAttribute =targetPhaseOne.targetAttribute;		//"目标属性"
								var annualTargetDatalist = targetPhaseOne.annualTargetDatalist;	//年度目标数组
								var indexdata = targetPhaseOne.indexEntityList;	//指标，包括：实施期、年度
								
								//追加实施其目标
								var targetNameOfImplphaseObj = $($('td .target-list')[0]);
								var implTargetindex = targetNameOfImplphaseObj.children().length + 1;
								var li = getTargetNameOfImplphaseLi(implTargetindex, targetNameOfImplphase, targetAttribute)
								targetNameOfImplphaseObj.append(li);
								
								//追加年度目标
								var aunnalTargetObj = $($('td .aunnal-target-list')[0]);
								var aunnalTargetIndex = aunnalTargetObj.children().length + 1;
								var aunnalTargetDiv = getAunnalTargetDivs(aunnalTargetIndex, annualTargetDatalist);
								aunnalTargetObj.append(aunnalTargetDiv);
					        	handleIndexData(indexdata);
					        }
					      //针对目标生成表格
							function handleIndexData(indexData) {
								var i = 0, len =indexData? indexData.length : 0, tempObj = null,
									firstIndex = "", secondIndex="", thirdIndex="",
									indexValue = "", targetType = "",
									firstConstant = "firstIndex", secondConstant = "secondIndex",
									filledConstant = "filled", notfilledConstant = "notFilled",
									trList = [], trListLen = 0, tr = {}, firstTd = {}, tdRowspan = 0,
									tdListFilled = [], tdListFilledLen = tdListFilled.length, indexObj = {},
									tdListNotFilled = [], tdListNotFilledLen = tdListNotFilled.length, notFilledObj = {},
									filledParent = {}, notFilledParent = {}, j = 0,
									rowspanTdsList = [], rowspanTdsListLen = 0, tdTempRowSpan = "";
								
								var trId = "", trClass = "", tdClass="";
								for(i = 0; i<len; i++) {
									tempObj = indexData[i];
									firstIndex = tempObj['firstIndex'];
									secondIndex = tempObj['secondIndex'];
									thirdIndex = tempObj['thirdIndex'];
									indexValue = tempObj['indexValue']?tempObj['indexValue']: "";
									targetType = tempObj['targetType'];
									
									trId = firstConstant + firstIndex;
									trClass = secondConstant + "_" + firstIndex + '_' + secondIndex;
									tdClass = secondConstant + "_" + targetType + "_" + firstIndex + '_' + secondIndex;
									
									tr = $('#' + trId);
									
									trList = $('tr[class=' + trClass + ']');
									trListLen = trList.length;
									
									tdListFilled = $('.' + tdClass + '.' + filledConstant);
									tdListFilledLen = tdListFilled.length;
									
									tdListNotFilled = $('.' + tdClass + '.' + notfilledConstant);
									tdListNotFilledLen = tdListNotFilled.length;
									
									if(tdListNotFilledLen == 0) {
										//添加一个新的tr
										filledParent = $(tdListFilled[tdListFilledLen-1]).parent();
										indexObj = getIndexObj(trId, firstIndex, secondIndex, thirdIndex, indexValue, targetType, tdListFilledLen+1);
										$(filledParent).after(indexObj);
										
										//修改tr中第一个td的rowspan
										firstTd = tr.children()[0];
										tdRowspan = $(firstTd).attr('rowspan');
										$(firstTd).attr('rowspan', parseInt(tdRowspan)+1);
										
										//修改td上的rowspan
										changeTdRowSpan(trList, trClass);
									} else {
										//找到td直接复制
										putValueToTd(tdListNotFilled, tdClass, thirdIndex, indexValue, tdListFilledLen+1);
									} 
								}
								
								//修改tr中第一个td的rowspan
								function changeTdRowSpan(trList, trClass){
									var rowspanTdsList = $(trList[0]).find('td[class=' + trClass + ']'),
										i = 0, len = rowspanTdsList.length, tdTempRowSpan = 0;
									for(i=0; i<len; i++) {
										tdTempRowSpan = $(rowspanTdsList[i]).attr("rowspan");
										$(rowspanTdsList[i]).attr("rowspan", parseInt(tdTempRowSpan)+1);
									}
								}
								
								//找到notFIlled，然后添加值
								function putValueToTd(tdListNotFilled, tdClass, thirdIndex, indexValue, tdListFilledLen) {
									var notFilledTdObj = $(tdListNotFilled[0]);
									notFilledTdObj.html('指标' + tdListFilledLen + ':' + thirdIndex);
									notFilledTdObj.next().html(indexValue);
									notFilledTdObj.removeClass("notFilled").addClass("filled");
								}
								
								
								function getIndexObj(trId, firstIndex, secondIndex, thirdIndex, indexValue, targetType, no) {
									if(targetType == 0) {
										return ['<tr id="' + trId + '" class="secondIndex_' + firstIndex + '_' + secondIndex + '">',
										        '<td class="'+ 'secondIndex_0_' + firstIndex + '_' + secondIndex + ' filled">' + "指标" + no +':' + thirdIndex + '</td>',
										      	'<td>' + indexValue + '</td>',
										      	'<td class="secondIndex_1_' + firstIndex + '_' + secondIndex + ' notFilled"></td>',
										      	'<td></td>',
										      	'</tr>'].join("");
									} else if(targetType == 1) {
										return ['<tr id="' + trId + '" class="secondIndex_' + firstIndex + '_' + secondIndex + '">',
										        '<td class="'+ 'secondIndex_0_' + firstIndex + '_' + secondIndex + ' notFilled"></td>',
										      	'<td></td>',
										      	'<td class="secondIndex_1_' + firstIndex + '_' + secondIndex + ' filled">' + "指标" + no +':' + thirdIndex + '</td>',
										      	'<td>' + indexValue + '</td>',
										      	'</tr>'].join("");
									} else {
										return;
									}
								}
							}
						 }
	        		});
		        	function getTargetNameOfImplphaseLi(index, targetNameOfImplphase, targetAttribute) {
						return '<li><a href="javascript:void(0)">目标' + index 
									+ '：</a><span>名称：' + targetNameOfImplphase //'实施期目标实施期目标'
									+ '</span></li>';
					}
					
					function getAunnalTargetDivs(aunnalTargetIndex, annualTargetDatalist) {
						var len = annualTargetDatalist? annualTargetDatalist.length : 0, i = 0, resultStr = "";
						
						for(i=0; i<len; i++) {
							resultStr += '<div>目标' + parseInt(aunnalTargetIndex+i) + '： '+ annualTargetDatalist[i]['annualTargets'] + '</div>' + '\n';
						}
						return resultStr;
					}
		        },
		        'click .checkAudit': function(e, value, row, index) {
		        	var modal = $('#checkReport');
		        	$('#contentNav').data('auditState', {'reportId': row.id, type: "check", auditArr: (row.auditList? row.auditList: [])});
		        	 orange.loadPage(
		        			{url: "system/getPage.service?path=manage/department/auditReport",
							 target: "checkReport_modal_body", 
							 selector: "#subTable", 
							 success: function(response){
								$('#subContent').data('auditState', {'reportId': row.id, type: "check", rowdata: row});
						        var modal = $('#checkReport');
						        //弹出模态框
						        modal.modal({backdrop: "static"});
							 }
		        		});
		        },
		        'click .reCreate': function(e, value, row, index) {
		        	$('#contentNav').data('provinceState', {'reportId': row.id, type: "reCreate", rowdata: row});
		        	$('#contentNav').data("regionTarget").selectItem(0);
		        }
		    };
	    
	    //加载全部
	    function ajaxRequest() {
	    	var year = $.trim($('#province_year').val()), 
				timesOfReport =$('#province_times').val(),
				nameOfSpecialProject = $("#province_name").val(),
				projectStatus = $("#province_state").val(),
				auditResult = $("#province_level").val();
	    	
	    	var paramData = {
	    			year:year,
	    			timesOfReport:timesOfReport,
	    			nameOfSpecialProject:nameOfSpecialProject,
	    			projectStatus:projectStatus,
	    			auditResult:auditResult
	    		};
	    	
	    	$.ajax({
				url:"report/retrieveReport.service",
				type:"post",
				data: paramData,
				success: function(data) {
					$table.bootstrapTable('load', data.data);
				},
				complete: function() {
				}
			});
	    }
	    
	    
		initTable();//初始化table
	});
	
})();
